#include "Renderer.h"
#include <iostream>

Renderer::Renderer(Mesh * mesh)
{
	Mesh::SubMeshIterator subMeshIt = mesh->getSubMeshStartIter();

	glId = glGenLists(1);
	glNewList(glId, GL_COMPILE);
	glEnable(GL_TEXTURE_2D);

	for (; subMeshIt != mesh->getSubMeshEndIter(); ++subMeshIt)
	{
		SubMesh * subMesh = (*subMeshIt);
		TriangleIter triIt = subMesh->getTriangleStartIter();

		glBindTexture(GL_TEXTURE_2D, subMesh->getTextureId());

		for (; triIt != subMesh->getTriangleEndIter(); ++triIt)
		{
			TRIANGLE * face = (*triIt);
			glBegin(GL_TRIANGLES);

			TEXCOORD * t1 = mesh->getTexCoordAt(face->tIndex[0]);
			glTexCoord2f(t1->s, t1->t);
			VERTEX * v1 = mesh->getVertexAt(face->vIndex[0]);
			glVertex3f(v1->x, v1->y, v1->z);
			TEXCOORD * t2 = mesh->getTexCoordAt(face->tIndex[1]);
			glTexCoord2f(t2->s, t2->t);
			VERTEX * v2 = mesh->getVertexAt(face->vIndex[1]);
			glVertex3f(v2->x, v2->y, v2->z);
			TEXCOORD * t3 = mesh->getTexCoordAt(face->tIndex[2]);
			glTexCoord2f(t3->s, t3->t);
			VERTEX * v3 = mesh->getVertexAt(face->vIndex[2]);
			glVertex3f(v3->x, v3->y, v3->z);

			glEnd();
		}
	}

	glDisable(GL_TEXTURE_2D);
	glEndList();
}

void Renderer::render()
{
	glEnable(GL_TEXTURE_2D);
	glPushMatrix();
	glCallList(glId);
	glPopMatrix();
	glDisable(GL_TEXTURE_2D);
}
